import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import GlitchBackgroundWrapper from '../../components/layout/GlitchBackgroundWrapper';
import { motion } from 'framer-motion';

const SignupPage: React.FC = () => {
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  });
  const [isLoading, setIsLoading] = useState(false);
  const [error] = useState('');

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 验证密码确认
    if (formData.password !== formData.confirmPassword) {
      alert('Passwords do not match');
      return;
    }

    setIsLoading(true);
    
    try {
      // 发送注册请求到后端
      const response = await fetch('/api/v1/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: formData.username,
          email: formData.email,
          password: formData.password
        }),
      });

      if (response.ok) {
        // 注册成功，跳转到登录页面
        alert('Registration successful! Please login.');
        navigate('/login');
      } else {
        // 注册失败，显示错误信息
        const errorData = await response.json();
        alert(`Registration failed: ${errorData.detail || 'Unknown error'}`);
      }
    } catch (error) {
      console.error('Registration error:', error);
      alert('Registration failed: Network error');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <GlitchBackgroundWrapper>

      {/* 导航栏 */}
      <motion.nav 
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          zIndex: 3,
          padding: '1rem 2rem',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          backgroundColor: 'rgba(0, 0, 0, 0.2)',
          backdropFilter: 'blur(10px)',
          borderBottom: '1px solid rgba(255, 255, 255, 0.1)'
        }}
        initial={{ y: -50, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.5 }}
      >
        <motion.div
          style={{
            display: 'flex',
            alignItems: 'center',
            color: 'white',
            fontWeight: 'bold',
            fontSize: '1.2rem',
            cursor: 'pointer'
          }}
          onClick={() => navigate('/')}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
        >
          <motion.span 
            style={{ marginRight: '0.5rem' }}
            animate={{ 
              rotate: [0, 10, -10, 0],
              transition: { 
                duration: 2,
                repeat: Infinity,
                repeatType: "reverse"
              }
            }}
          >
            ⚡
          </motion.span>
          React Bits
        </motion.div>
        <div style={{
          display: 'flex',
          gap: '2rem'
        }}>
          <motion.button
            onClick={() => navigate('/')}
            style={{
              color: 'white',
              background: 'none',
              border: 'none',
              fontSize: '1rem',
              fontWeight: '500',
              cursor: 'pointer',
              transition: 'all 0.3s ease'
            }}
            whileHover={{ scale: 1.1 }}
            whileTap={{ scale: 0.9 }}
            onMouseEnter={(e) => {
              (e.target as HTMLElement).style.color = '#61dca3';
            }}
            onMouseLeave={(e) => {
              (e.target as HTMLElement).style.color = 'white';
            }}
          >
            Back to Home
          </motion.button>
        </div>
      </motion.nav>

      {/* 注册表单区域 */}
      <div style={{
        position: 'relative',
        zIndex: 2,
        width: '100%',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        padding: '20px'
      }}>
        {/* 注册框 */}
        <motion.div 
          style={{
            width: '100%',
            maxWidth: '400px',
            padding: '2.5rem',
            backgroundColor: 'rgba(0, 0, 0, 0.4)',
            backdropFilter: 'blur(15px)',
            border: '1px solid rgba(255, 255, 255, 0.1)',
            borderRadius: '20px',
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
            position: 'relative',
            overflow: 'hidden'
          }}
          initial={{ opacity: 0, y: 50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          {/* 顶部装饰线 */}
          <div style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            height: '2px',
            background: 'linear-gradient(90deg, transparent, #61dca3, transparent)',
            animation: 'shimmer 2s infinite'
          }} />

          {/* 标题 */}
          <motion.div 
            style={{
              textAlign: 'center',
              marginBottom: '2rem'
            }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.5, delay: 0.2 }}
          >
            <h2 style={{
              fontSize: '2rem',
              fontWeight: 'bold',
              marginBottom: '0.5rem',
              background: 'linear-gradient(90deg, #ffffff, #61dca3)',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              animation: 'textGlow 3s ease-in-out infinite alternate'
            }}>
              注册
            </h2>
            <p style={{
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: '0.95rem',
              margin: 0
            }}>
              Create a new account
            </p>
          </motion.div>

          {/* 错误信息 */}
          {error && (
            <motion.div
              style={{
                color: '#ff6b6b',
                textAlign: 'center',
                marginBottom: '1rem',
                fontSize: '0.9rem'
              }}
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
            >
              {error}
            </motion.div>
          )}

          {/* 表单 */}
          <form onSubmit={handleSubmit} style={{ width: '100%' }}>
            <motion.div 
              style={{ marginBottom: '1.5rem' }}
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.3 }}
            >
              <label style={{
                display: 'block',
                color: 'rgba(255, 255, 255, 0.9)',
                fontSize: '0.9rem',
                fontWeight: '500',
                marginBottom: '0.5rem'
              }}>
                Username
              </label>
              <input
                type="text"
                name="username"
                value={formData.username}
                onChange={handleInputChange}
                required
                style={{
                  width: '100%',
                  padding: '12px 16px',
                  backgroundColor: 'rgba(255, 255, 255, 0.05)',
                  border: '1px solid rgba(255, 255, 255, 0.2)',
                  borderRadius: '10px',
                  color: 'white',
                  fontSize: '1rem',
                  outline: 'none',
                  transition: 'all 0.3s ease',
                  backdropFilter: 'blur(5px)',
                  boxSizing: 'border-box'
                }}
                onFocus={(e) => {
                  (e.target as HTMLElement).style.borderColor = '#61dca3';
                  (e.target as HTMLElement).style.boxShadow = '0 0 0 2px rgba(97, 220, 163, 0.2)';
                }}
                onBlur={(e) => {
                  (e.target as HTMLElement).style.borderColor = 'rgba(255, 255, 255, 0.2)';
                  (e.target as HTMLElement).style.boxShadow = 'none';
                }}
                placeholder="Enter your username"
              />
            </motion.div>

            <motion.div 
              style={{ marginBottom: '1.5rem' }}
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.4 }}
            >
              <label style={{
                display: 'block',
                color: 'rgba(255, 255, 255, 0.9)',
                fontSize: '0.9rem',
                fontWeight: '500',
                marginBottom: '0.5rem'
              }}>
                Email Address
              </label>
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
                required
                style={{
                  width: '100%',
                  padding: '12px 16px',
                  backgroundColor: 'rgba(255, 255, 255, 0.05)',
                  border: '1px solid rgba(255, 255, 255, 0.2)',
                  borderRadius: '10px',
                  color: 'white',
                  fontSize: '1rem',
                  outline: 'none',
                  transition: 'all 0.3s ease',
                  backdropFilter: 'blur(5px)',
                  boxSizing: 'border-box'
                }}
                onFocus={(e) => {
                  (e.target as HTMLElement).style.borderColor = '#61dca3';
                  (e.target as HTMLElement).style.boxShadow = '0 0 0 2px rgba(97, 220, 163, 0.2)';
                }}
                onBlur={(e) => {
                  (e.target as HTMLElement).style.borderColor = 'rgba(255, 255, 255, 0.2)';
                  (e.target as HTMLElement).style.boxShadow = 'none';
                }}
                placeholder="Enter your email"
              />
            </motion.div>

            <motion.div 
              style={{ marginBottom: '1.5rem' }}
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.5 }}
            >
              <label style={{
                display: 'block',
                color: 'rgba(255, 255, 255, 0.9)',
                fontSize: '0.9rem',
                fontWeight: '500',
                marginBottom: '0.5rem'
              }}>
                Password
              </label>
              <input
                type="password"
                name="password"
                value={formData.password}
                onChange={handleInputChange}
                required
                style={{
                  width: '100%',
                  padding: '12px 16px',
                  backgroundColor: 'rgba(255, 255, 255, 0.05)',
                  border: '1px solid rgba(255, 255, 255, 0.2)',
                  borderRadius: '10px',
                  color: 'white',
                  fontSize: '1rem',
                  outline: 'none',
                  transition: 'all 0.3s ease',
                  backdropFilter: 'blur(5px)',
                  boxSizing: 'border-box'
                }}
                onFocus={(e) => {
                  (e.target as HTMLElement).style.borderColor = '#61dca3';
                  (e.target as HTMLElement).style.boxShadow = '0 0 0 2px rgba(97, 220, 163, 0.2)';
                }}
                onBlur={(e) => {
                  (e.target as HTMLElement).style.borderColor = 'rgba(255, 255, 255, 0.2)';
                  (e.target as HTMLElement).style.boxShadow = 'none';
                }}
                placeholder="Enter your password"
              />
            </motion.div>

            <motion.div 
              style={{ marginBottom: '2rem' }}
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.6 }}
            >
              <label style={{
                display: 'block',
                color: 'rgba(255, 255, 255, 0.9)',
                fontSize: '0.9rem',
                fontWeight: '500',
                marginBottom: '0.5rem'
              }}>
                Confirm Password
              </label>
              <input
                type="password"
                name="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleInputChange}
                required
                style={{
                  width: '100%',
                  padding: '12px 16px',
                  backgroundColor: 'rgba(255, 255, 255, 0.05)',
                  border: '1px solid rgba(255, 255, 255, 0.2)',
                  borderRadius: '10px',
                  color: 'white',
                  fontSize: '1rem',
                  outline: 'none',
                  transition: 'all 0.3s ease',
                  backdropFilter: 'blur(5px)',
                  boxSizing: 'border-box'
                }}
                onFocus={(e) => {
                  (e.target as HTMLElement).style.borderColor = '#61dca3';
                  (e.target as HTMLElement).style.boxShadow = '0 0 0 2px rgba(97, 220, 163, 0.2)';
                }}
                onBlur={(e) => {
                  (e.target as HTMLElement).style.borderColor = 'rgba(255, 255, 255, 0.2)';
                  (e.target as HTMLElement).style.boxShadow = 'none';
                }}
                placeholder="Confirm your password"
              />
            </motion.div>

            {/* 注册按钮 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3, delay: 0.7 }}
            >
              <button
                type="submit"
                disabled={isLoading}
                style={{
                  width: '100%',
                  padding: '14px',
                  fontSize: '1.1rem',
                  fontWeight: 'bold',
                  color: isLoading ? 'rgba(255, 255, 255, 0.7)' : 'black',
                  backgroundColor: isLoading ? 'rgba(97, 220, 163, 0.5)' : '#61dca3',
                  border: 'none',
                  borderRadius: '12px',
                  cursor: isLoading ? 'not-allowed' : 'pointer',
                  transition: 'all 0.3s ease',
                  position: 'relative',
                  overflow: 'hidden'
                }}
                onMouseEnter={(e) => {
                  if (!isLoading) {
                    (e.target as HTMLElement).style.backgroundColor = '#4fc085';
                    (e.target as HTMLElement).style.transform = 'translateY(-1px)';
                    (e.target as HTMLElement).style.boxShadow = '0 6px 20px rgba(97, 220, 163, 0.4)';
                  }
                }}
                onMouseLeave={(e) => {
                  if (!isLoading) {
                    (e.target as HTMLElement).style.backgroundColor = '#61dca3';
                    (e.target as HTMLElement).style.transform = 'translateY(0)';
                    (e.target as HTMLElement).style.boxShadow = 'none';
                  }
                }}
              >
                {isLoading ? (
                  <span style={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: '0.5rem'
                  }}>
                    <div style={{
                      width: '16px',
                      height: '16px',
                      border: '2px solid rgba(255, 255, 255, 0.3)',
                      borderTop: '2px solid white',
                      borderRadius: '50%',
                      animation: 'spin 1s linear infinite'
                    }} />
                    Signing Up...
                  </span>
                ) : (
                  'Sign Up'
                )}
              </button>
            </motion.div>
          </form>

          {/* 底部链接 */}
          <motion.div 
            style={{
              marginTop: '1.5rem',
              textAlign: 'center',
              paddingTop: '1.5rem',
              borderTop: '1px solid rgba(255, 255, 255, 0.1)'
            }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.5, delay: 0.8 }}
          >
            <p style={{
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: '0.9rem',
              margin: 0
            }}>
              Already have an account? {' '}
              <motion.button
                style={{
                  background: 'none',
                  border: 'none',
                  color: '#61dca3',
                  fontSize: '0.9rem',
                  fontWeight: '500',
                  cursor: 'pointer',
                  textDecoration: 'underline'
                }}
                onClick={() => navigate('/login')}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.9 }}
              >
                Sign in
              </motion.button>
            </p>
          </motion.div>
        </motion.div>
      </div>

      {/* CSS 动画样式 */}
      <style>
        {`
          @keyframes fadeInUp {
            from {
              opacity: 0;
              transform: translateY(30px);
            }
            to {
              opacity: 1;
              transform: translateY(0);
            }
          }

          @keyframes shimmer {
            0% {
              transform: translateX(-100%);
            }
            100% {
              transform: translateX(100%);
            }
          }

          @keyframes textGlow {
            0% {
              text-shadow: 0 0 10px rgba(97, 220, 163, 0.3);
            }
            100% {
              text-shadow: 0 0 20px rgba(97, 220, 163, 0.6), 0 0 30px rgba(97, 220, 163, 0.4);
            }
          }

          @keyframes spin {
            from {
              transform: rotate(0deg);
            }
            to {
              transform: rotate(360deg);
            }
          }

          /* 输入框占位符样式 */
          input::placeholder {
            color: rgba(255, 255, 255, 0.5);
          }

          /* 滚动条样式 - 深色主题 */
          ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
          }

          ::-webkit-scrollbar-track {
            background: #1a1a1a;
            border-radius: 4px;
          }

          ::-webkit-scrollbar-thumb {
            background: #444;
            border-radius: 4px;
          }

          ::-webkit-scrollbar-thumb:hover {
            background: #666;
          }

          /* 滚动条样式 - 浅色主题 */
          [data-theme="light"] ::-webkit-scrollbar-track {
            background: #f0f2f5;
            border-radius: 4px;
          }

          [data-theme="light"] ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
          }

          [data-theme="light"] ::-webkit-scrollbar-thumb:hover {
            background: #a1a1a1;
          }

          /* Firefox 滚动条样式 */
          html {
            scrollbar-width: thin;
            scrollbar-color: #444 #1a1a1a;
          }

          [data-theme="light"] html {
            scrollbar-color: #c1c1c1 #f0f2f5;
          }

          /* 导航栏按钮样式 */
          nav button {
            color: white;
            background: none;
            border: none;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
          }

          nav button:hover {
            color: #61dca3;
          }
        `}
      </style>
    </GlitchBackgroundWrapper>
  );
};

export default SignupPage;